package zero.tech.games.gate.timer;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import com.alibaba.fastjson.JSONObject;

import zero.tech.games.common.QueueConsts;
import zero.tech.games.common.ThreadRunner;
import zero.tech.games.entity.games.UserOnline;
import zero.tech.games.gate.mapper.UserOnlineMapper;
import zero.tech.redis.queue.QueueUtil;

@Configuration
public class UserOnlineStatusQueue extends ThreadRunner{
	private static final Logger logger=LoggerFactory.getLogger(UserOnlineStatusQueue.class);
	@Autowired
	private QueueUtil queueUtil;
	@Autowired
	private UserOnlineMapper userOnlineMapper;
	@Override
	public void process() {
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				handle();
			}
		}).start();
	}

	protected void handle() {
		while(true) {
			int sleep = 0;
			List<String> list = queueUtil.pullQueueBatch(QueueConsts.QUEUE_ONLINE_STATUS, 100);
			try {
				if (list == null || list.isEmpty()) {
					sleep = 1000;
				} else {
					// 开始处理业务
					long time = System.currentTimeMillis();
					logger.info("============================开始在线状态入库==============================");
					
					Map<Integer,UserOnline> map=new HashMap<>();
					for(String str:list) {
						UserOnline userOnline = JSONObject.parseObject(str,UserOnline.class);
						map.put(userOnline.getUid(), userOnline);
					}
					if(!map.isEmpty()) {
						List<UserOnline>onlines=new ArrayList<UserOnline>();
						onlines.addAll(map.values());
						userOnlineMapper.insertOrUpdateBatch(onlines);
					}
					logger.info("=====================结束在线状态入库,操作耗时:{}毫秒========================",
							(System.currentTimeMillis() - time));
				}
			} catch (Exception e) {
				e.printStackTrace();
				sleep = 1000;
			}
			if (sleep != 0) {
				try {
					Thread.sleep(sleep);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}		
	}

}
